<template>
  <a-spin :spinning="confirmLoading">
    <a-form :form="form">
      <a-row>
        <!-- 表单数据 -->
        <ZcglRecipientsInfo   :allall="allall"   ref="recipientsInfo"></ZcglRecipientsInfo>


        <a-col :span="24" style="margin-top: 15px"  >
          <a-form-item label="标题" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
<!--            <a-input v-if="!disabled" v-decorator="['title', validatorRules.title]" rows="4" placeholder="请输入标题" />-->
            <a-input   disabled="true"  v-if="!disabled" v-decorator="['title']" rows="4" placeholder="系统自动生成" />
            <span v-else>{{ data.title }}</span>
          </a-form-item>
        </a-col>

<!--        <a-col :span="24">-->
<!--          <a-form-item label="申请说明" :labelCol="labelCol2" :wrapperCol="wrapperCol2">-->
<!--            <a-textarea v-if="!disabled" v-decorator="['processDescription', validatorRules.processDescription]"-->
<!--                        rows="4" placeholder="请输入申请说明" />-->
<!--            <span v-else>{{ data.processDescription }}</span>-->
<!--          </a-form-item>-->
<!--        </a-col>-->

      </a-row>
    </a-form>
    <BaseForm v-show="false" v-if="!disabled" ref="baseForma"   ></BaseForm>
    <a-form-item v-if="!disabled"
                 :wrapperCol="{ span: 24 }"
                 style="text-align: center">
<!--      <a-button type="primary" :disabled="disabled || btndisabled" @click="handleSubmit">保存</a-button>-->
      <a-button style="margin-left: 8px" type="primary" :disabled="disabled || btndisabled"
                @click="handleSubmitAndShenPi">保存并审批
      </a-button>
      <a-button style="margin-left: 8px" :disabled="disabled" @click="close">取消</a-button>
    </a-form-item>
    <a-form-item v-if="task"
                 :wrapperCol="{ span: 24 }"
                 style="text-align: center">
      <a-button type="primary" @click="passTask">通过</a-button>
      <a-button style="margin-left: 8px" @click="backTask">驳回</a-button>
    </a-form-item>
  </a-spin>
</template>
<script>
import store from '@/store'
import ZcglRecipientsInfo from './ZcglRecipientsInfo'
import BaseForm from './BaseForm'
import JEditableTable from '../../../components/jeecg/JEditableTable'
import JDate from '../../../components/jeecg/JDate'
import JSearchSelectTag from '../../../components/dict/JSearchSelectTag'
import { ActivitiFormMixin } from '../mixins/activitiFormMixin'
import { AssetSubMixin } from '../../../api/assetSubMixin'
import { httpAction, putAction } from '../../../api/manage'
import pick from 'lodash.pick'
import { VALIDATE_NO_PASSED, validateFormAndTables } from '../../../utils/JEditableTableUtil'
import { actBusinessAdd, actBusinessEdit } from '../../../api/actBusiness'
export default {
  name: 'ZcglRecipientsAdd',
  mixins: [ActivitiFormMixin, AssetSubMixin],
  components: {
    BaseForm,
    ZcglRecipientsInfo,
    JEditableTable,
    JDate,
    JSearchSelectTag
  },
  data () {
    return {
      allall:"",
      tableId:"",
      checkResult:"",
      disableSubmit:false,
      // form
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      validatorRules: {
        title: {
          rules: [
            { required: true, message: '请输入标题!' }
          ]
        },
        processDescription: {
          rules: [
            { required: true, message: '请输入申请说明!' }
          ]
        }
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    setValue () {

      this.$refs.recipientsInfo.disableSubmit = this.disabled

      this.$refs.recipientsInfo.showModal(this.data.dataMap)
      this.$refs.recipientsInfo.liuchengbianji = this.processData.liuchengbianji
      this.$refs.recipientsInfo.tableId = this.processData.tableId
      this.allall = this.processData.all

      if(this.processData.title!=null){
        this.data.title = this.processData.title
      }else{
        this.data.title = this.processData.titleContent
      }
      if (!this.disabled) {
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.data, 'processDescription', 'title',))
          if (this.processData.procDefId) {
            let keys = []
            keys.push(this.processData.procDefId)
            this.$refs.baseForma.selectedRowKeys = keys
          }
          this.$refs.baseForma.queryParam = { status: 1, routeName: this.processData.routeName }
          this.$refs.baseForma.loadData(1)
        })
      }
    },

    wzData(v){
      //
      alert("进入啊"+JSON.stringify(v))
    },

    handleSubmitAndShenPi() {

      let that = this
      /** 触发表单验证 */
      this.$refs.recipientsInfo.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormAndTables(this.$refs.recipientsInfo.form, tables)
      }).then(allValues => {
        if (typeof this.$refs.recipientsInfo.classifyIntoFormData !== 'function') {
          throw this.$refs.recipientsInfo.throwNotFunction('classifyIntoFormData')
        }
        let a = this.$refs.recipientsInfo.classifyIntoFormData(allValues)



        for (let i = 0; i < a.zcglRecipientsAssetsList.length; i++) {
          var item = a.zcglRecipientsAssetsList[i]
          if(parseFloat(item.assetAmount) > parseFloat(item.trueCount)){
            this.$message.warn("编码为"+item.assetCode+"的领用数量"+item.assetAmount+"大于可领用数量"+item.trueCount+"，请仔细检查！")
            return
          }

          
        }



        //判断是否配置过，如果是的话
        //此处重新添加新的流程
        // httpAction("/zcgl/zcglTypeSettings/list", {"name":a.zcglRecipientsAssetsList[0].chwzType  }, 'post').then((res) => {
          // if (res.success ) {
          //
          //   if(res.result.records.length>0 && a.zcglRecipientsAssetsList[0].chwzType!='' && a.zcglRecipientsAssetsList[0].chwzType!=null){
          //   //跳过流程 直接添加
          //     //此处重新添加新的流程
          //     delete a.id
          //     delete a.processStatus
          //     delete a.processStatusText
          //     delete a.createTime
          //     a.processStatusText = "自动生成";
          //     httpAction(this.$refs.recipientsInfo.url.adda, a, 'post').then((res) => {
          //       if (res.success) {
          //         //todo 关闭后的回调
          //         this.$emit('close')
          //         //调用刷新
          //         this.$emit('shuaxin')
          //         this.$message.success(res.message)
          //       } else {
          //
          //         this.$message.warning(res.message)
          //       }
          //     }).finally(() => {
          //       this.confirmLoading = false
          //     })
          //   }else {
              //此处判断类型，如果是办公类型，走办公类型的LC，如果是物资存货，走物资存货的流程 自动判断选择，不需要人工选择  低脂耗品
              // if(a.zcglRecipientsAssetsList[0].assetType == '易耗品'){
              //   let keys = []
              //   keys.push( this.$refs.baseForma.dataSource[0].id)
              //   this.$refs.baseForma.selectedRowKeys = keys
              //   // alert(JSON.stringify(this.$refs.baseForma.dataSource[0]))
              // }
              // //办公用品
              // if(a.zcglRecipientsAssetsList[0].assetType == '办公用品'){
              //   let keys = []
              //   keys.push( this.$refs.baseForma.dataSource[1].id)
              //
              //   this.$refs.baseForma.selectedRowKeys = keys
              // }
              // //存货物资
              // if(a.zcglRecipientsAssetsList[0].assetType == '存货物资'){
              //   let keys = []
              //   keys.push( this.$refs.baseForma.dataSource[2].id)
              //   this.$refs.baseForma.selectedRowKeys = keys
              // }
        let keys = []
        keys.push( this.$refs.baseForma.dataSource[0].id)
        this.$refs.baseForma.selectedRowKeys = keys
              this.form.validateFields((err, values) => {
                if (!err) {
                  //不需要判断了，因为自动赋值了
                  // if (this.$refs.baseForma.selectedRowKeys.length != 1) {
                  //   this.$message.warning('请选择流程图')
                  //   return
                  // }
                  this.confirmLoading = true
                  // httpAction(this.$refs.recipientsInfo.url.edit, a, 'put').then((res) => {

                  if(a.id == '1590665592578457602'){
                    delete a.id
                  }
                  delete a.processStatus
                  delete a.processStatusText
                  delete a.createTime
                  a.processStatusText = "启动";
                  for (let i = 0; i < a.zcglRecipientsAssetsList.length; i++) {
                    var item = a.zcglRecipientsAssetsList[i]
                    delete item.id
                  }


                  if(this.processData.tableId!=null  && this.processData.tableId !='1590665592578457602' ){


                    //此处重新添加新的流程
                    a.id = this.processData.tableId


                    putAction(this.$refs.recipientsInfo.url.edit, a, 'post').then((res) => {
                      if (res.success) {
                        let formData = values
                        formData.data = a
                        formData.procDefId = this.$refs.baseForma.selectedRowKeys[0]

                        // formData.procDefId = this.$refs.baseForma.selectedRowKeys
                        var orderNo = res.result.orderNo


                        var date = new Date();
                        var hour = date.getHours(); // 时
                        var minutes = date.getMinutes(); // 分
                        var seconds = date.getSeconds() //秒
                        formData.titleContent = orderNo+hour+minutes+seconds;

                        //修改tableid
                        formData.tableId = res.result.id
                        that.handleSubmitVaAndShenPi(formData)
                      } else {
                        this.$message.warning(res.message)
                      }
                    }).finally(() => {
                      this.confirmLoading = false
                    })
                  }else{




                    //此处重新添加新的流程
                    httpAction(this.$refs.recipientsInfo.url.add, a, 'post').then((res) => {
                      if (res.success) {
                        let formData = values
                        formData.data = a
                        formData.procDefId = this.$refs.baseForma.selectedRowKeys[0]
                        // formData.procDefId = this.$refs.baseForma.selectedRowKeys
                        var orderNo = res.result.orderNo
                        formData.titleContent = orderNo
                        //修改tableid
                        formData.tableId = res.result.id
                        that.handleSubmitVaAndShenPi(formData)
                      } else {
                        this.$message.warning(res.message)
                      }
                    }).finally(() => {
                      this.confirmLoading = false
                    })

                  }



                }
              })
            // }
          // }
          // else {
          //
          // }
        // }).finally(() => {
        //
        // })




        // 发起请求
        // return this.request(formData)
      }).catch(e => {
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })

    },
    //保存并发起
    handleSubmitVaAndShenPi(values) {
      var that  = this;
      this.loading = true;
      //写在此文件中，是因为我想覆盖父亲，不想用父亲的保存
      let formData = values
     // formData.tableId = this.processData.tableId
      //这个是添加数据后返回的数据的编号，作为流程的标题发起，方便查找。
      var  titleContent =    formData.titleContent;
      formData.title = titleContent
      this.data.title =   formData.title
      let action

      let v = formData

      if (!this.isNew) {
        formData.id = this.processData.id

        // action = actBusinessEdit(formData)
        //这里他点击保存，实际上是添加了一条流程记录 很明显在这里执行的  我想要在这里直接 获取第一个节点，然后发起流程了
        //通过这个参数 是可以拿到第一个节点的  formData.procDefId  然后我默认节点审核人，就通过审核了赛
        action = actBusinessAdd(formData)
        this.btndisabled = true
        action.then((res) => {
          if (res.success) {
            // this.$message.success('保存成功')
            //保存成功然后发起流程
            // 加载审批人
            this.getAction("/actProcessIns/getFirstNode",{procDefId:formData.procDefId}).then(resT => {
              var params = {};
              // 默认勾选
              var idss = [];
              resT.result.users.forEach(e => {
                idss.push(e.username);
              });
              params.assignees = idss.join(",")
              //此处，设置默认为普通级别的就行
              params.priority = 0;
              params.firstGateway = false;
              params.sendMessage = true;
              params.procDefId = formData.procDefId;
              params.title = formData.title;
              params.id = res.message
              this.postParamsAction("/actBusiness/apply",params).then(res => {
                if (res.success) {
                  alert("发起流程成功")
                  this.$message.success("保存并发起流程成功");
                  // that.loadData();
                  this.modalVisible = false;
                  // return
                  //设置等待 不然没办法刷新的  然后流程的状态就还是草稿中
                  setTimeout(() => {
                    this.loading = false;
                    this.$emit('afterSubmit', formData)
                  }, 2000);
                }else {
                  this.$message.error(res.message)
                }
              }).finally();
            });
          } else {
            this.$message.error(res.message)
          }
        }).finally(() => {
          this.btndisabled = false
        })
      } else {
        //这里他点击保存，实际上是添加了一条流程记录 很明显在这里执行的  我想要在这里直接 获取第一个节点，然后发起流程了
        //通过这个参数 是可以拿到第一个节点的  formData.procDefId  然后我默认节点审核人，就通过审核了赛
        action = actBusinessAdd(formData)
        this.btndisabled = true
        action.then((res) => {
          if (res.success) {
            // this.$message.success('保存成功')
            //保存成功然后发起流程
            // 加载审批人
            this.getAction("/actProcessIns/getFirstNode",{procDefId:formData.procDefId}).then(resT => {
              var params = {};
              // 默认勾选
              var idss = [];
              resT.result.users.forEach(e => {
                idss.push(e.username);
              });
              params.assignees = idss.join(",")
              //此处，设置默认为普通级别的就行
              params.priority = 0;
              params.firstGateway = false;
              params.sendMessage = true;
              params.procDefId = formData.procDefId;
              params.title = formData.title;
              params.id = res.message
              this.postParamsAction("/actBusiness/apply",params).then(res => {
                if (res.success) {
                  alert("发起流程成功")
                  this.$message.success("保存并发起流程成功");
                  // that.loadData();
                  this.modalVisible = false;
                  // return
                  //设置等待 不然没办法刷新的  然后流程的状态就还是草稿中
                  setTimeout(() => {
                    this.loading = false;
                    this.$emit('afterSubmit', formData)
                  }, 2000);
                }else {
                  this.$message.error(res.message)
                }
              }).finally();
            });
          } else {
            this.$message.error(res.message)
          }
        }).finally(() => {
          this.btndisabled = false
        })
      }


    },
    // handler
    handleSubmit (e) {
      let that = this
      /** 触发表单验证 */
      this.$refs.recipientsInfo.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormAndTables(this.$refs.recipientsInfo.form, tables)
      }).then(allValues => {
        if (typeof this.$refs.recipientsInfo.classifyIntoFormData !== 'function') {
          throw this.$refs.recipientsInfo.throwNotFunction('classifyIntoFormData')
        }
        let a = this.$refs.recipientsInfo.classifyIntoFormData(allValues)

        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.$refs.baseForma.selectedRowKeys.length != 1) {
              this.$message.warning('请选择流程图')
              return
            }
            this.confirmLoading = true
            httpAction(this.$refs.recipientsInfo.url.edit, a, 'put').then((res) => {
              if (res.success) {
                let formData = values
                formData.data = a
                formData.procDefId = this.$refs.baseForma.selectedRowKeys[0]
                that.handleSubmitVa(formData)
              } else {
                this.$message.warning(res.message)
              }
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        })
        // 发起请求
        // return this.request(formData)
      }).catch(e => {
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
    }
  }
}
</script>
